﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using Sims3Package.Wrapper;

namespace PackageEditor.Helper
{
    public partial class STBLHelper : Form
    {
        public STBLResourceWrapper w;
        public STBLHelper(Stream s)
        {
            InitializeComponent();
            w = new STBLResourceWrapper(s);
        }

        private void STBLHelper_Load(object sender, EventArgs e)
        {
            this.Icon = Properties.Resources.Icon;
            if (w.StringEntries == null) w.StringEntries = new Dictionary<ulong, string>();
            foreach (var kvp in w.StringEntries)
            {
                this.listBox.Items.Add(new Item(kvp));
            }
            
        }

        public class Item
        {
            public UInt64 Hash { get; set; }
            public string Value { get; set; }
            public Item(KeyValuePair<ulong, string> kvp)
            {
                this.Hash = kvp.Key;
                this.Value = kvp.Value;
            }
            public Item(ulong hash, string value)
            {
                this.Hash = hash;
                this.Value = value;
            }
            public override string ToString()
            {
                return string.Format("0x{0:X16}", Hash);
            }
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            if (listBox.SelectedIndex < 0) return;
            listBox.Items.RemoveAt(listBox.SelectedIndex);
        }

        private void listBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox.SelectedIndex < 0) return;
            Item item = listBox.SelectedItem as Item;
            txtValue.Text = item.Value;
            txtName.Text = string.Format("0x{0:X16}", item.Hash);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (w.StringEntries == null) this.DialogResult = System.Windows.Forms.DialogResult.No;
            w.StringEntries = new Dictionary<ulong, string>(this.listBox.Items.Count);
            foreach (Item item in listBox.Items)
                w.StringEntries.Add(item.Hash, item.Value);
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            ulong hash = ResourceForm.FNV64Hash(txtName.Text);
            this.listBox.Items.Add(new Item(hash, txtValue.Text));
        }
    }
}
